package com.fmh.mybatisplus.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fmh.mybatisplus.comoon.vo.Result;
import com.fmh.mybatisplus.mapper.UserMapper;
import com.fmh.mybatisplus.pojo.Role;
import com.fmh.mybatisplus.pojo.User;
import com.fmh.mybatisplus.pojo.UserRole;
import com.fmh.mybatisplus.service.RoleService;
import com.fmh.mybatisplus.service.UserRoleService;
import com.fmh.mybatisplus.service.UserService;
import com.fmh.mybatisplus.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;

    @GetMapping("/userInfo/{id}")
    public Result userInfo(@PathVariable Long id) {
        User user = userService.getById(id);
        // 断言进行判断
        Assert.notNull(user, "找不到管理员");

        // 根据id查询角色
        List<Role> roles = roleService.listRolesByUserId(id);
        user.setRoles(roles);

        return Result.success(user);
    }

    @GetMapping("/info")
    public Result info(Principal principal) {
        User user = userService.getByUserName(principal.getName());
        return Result.success(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar", user.getAvatarUrl())
                .map()
        );
    }

    @GetMapping("/list")
    public Result list(
            @RequestParam Integer current,
            @RequestParam Integer size,
            @RequestParam(defaultValue = "") String username
    ) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("username", username);

        Page<User> page = new Page<>(current, size);
        Page<User> pageData = userService.page(page, wrapper);

        // 查询所拥有的角色
        pageData.getRecords().forEach(u -> {
            u.setRoles(roleService.listRolesByUserId(u.getId()));
        });

        return Result.success(pageData);
    }

    @GetMapping("/{id}")
    public Result listById(@PathVariable Integer id) {
        User user = userMapper.selectById(id);
        return Result.success(user);
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        int i = userMapper.deleteById(id);
        return Result.success();
    }

    @PostMapping("/assign/{userId}")
    public Result assignRoles(@PathVariable Long userId, @RequestBody Long[] roleIds) {
        // 存储拆分的数据
        List<UserRole> userRoles = new ArrayList<>();
        // 循环
        Arrays.stream(roleIds).forEach(r -> {
            UserRole userRole = new UserRole();
            userRole.setRoleId(r);
            userRole.setUserId(userId);
            //保存
            userRoles.add(userRole);
        });

        // 先删除原来的记录，再保存新的
        userRoleService.remove(new QueryWrapper<UserRole>().eq("user_id", userId));
        userRoleService.saveBatch(userRoles);
//        // 先获取用户信息再删除redis缓存
        User user = userService.getById(userId);
//        userService.clearUserAuthorityInfo(user.getUsername());
        // 返回
        return Result.success(roleIds);


    }

    @PostMapping
    public Result insert(@RequestBody User user) {
        int i = userMapper.insert(user);
        return Result.success();
    }

    @PatchMapping
    public Result update(@RequestBody User user) {
        int i = userMapper.updateById(user);
        return Result.success();
    }
}
